import { lazy } from 'react';
import { createHashRouter, Navigate, redirect } from 'react-router-dom';
import NProgress from 'nprogress';
import store from '../store';
import { clearQueue } from '../store/cancelReq';
import { routerChangeListener } from '../utils';
NProgress.inc(0.2);
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false });
NProgress.done();
const Login = lazy(() => import('../views/Login'));
const Home = lazy(() => import('../views/Home'));
const Demo = lazy(() => import('../views/Demo'));

function AuthLoader() {
  if (!store.getState().user.token) {
    return redirect('/login');
  }
  return {};
}

store.dispatch(clearQueue());
routerChangeListener(() => {
  store.dispatch(clearQueue());
  NProgress.start();
  Promise.resolve().then(() => NProgress.done());
});

export default createHashRouter([
  {
    path: '/',
    element: <Navigate replace to='/home' />,
  },
  {
    path: '/login',
    element: <Login />,
  },
  {
    path: '/home',
    loader: AuthLoader,
    element: <Home />,
  },
  {
    path: '/demo',
    element: <Demo />,
  },
]);
